package com.devehx.wallet.task;

import com.devehx.wallet.comm.RechargeState;
import com.devehx.wallet.comm.TxState;
import com.devehx.wallet.comm.WalletKit;
import com.devehx.wallet.model.Recharge;
import com.devehx.wallet.serviceimpl.RechargeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Slf4j
@Component
public class RechargeStateConfirmTask {

    @Resource
    private RechargeService rechargeService;

    @Scheduled(fixedDelay = 10000)
    public void collect() {
        List<Recharge> recharges = rechargeService.findNoCollectList();
        if (Objects.isNull(recharges) || recharges.size() < 1) {
            return;
        }
        recharges.forEach(rechargeService::collect);
    }

    @Scheduled(fixedDelay = 10000)
    @Transactional(rollbackFor = Exception.class)
    public void confirm() {
        List<Recharge> recharges = rechargeService.findNoConfirmList();
        if (Objects.isNull(recharges) || recharges.size() < 1) {
            return;
        }
        for (Recharge recharge : recharges) {
            //交易哈希
            String txHash = recharge.getTxHash();
            TxState state = WalletKit.queryTx(txHash);
            if (TxState.CONFIRMED.equals(state)) {
                rechargeService.changeState(recharge.getId(), RechargeState.OK);
            } else if (TxState.FAIL.equals(state)) {
                rechargeService.changeState(recharge.getId(), RechargeState.NO);
            }
        }
    }


}
